package net.tp.struct.adt;

import java.util.*;

public class DoublyNode<E> {

    public E element;

    public DoublyNode<E> prev;

    public DoublyNode<E> next;

    public DoublyNode(E element) {
        this(element, null, null);
    }

    public DoublyNode(E element, DoublyNode<E> prev, DoublyNode<E> next) {
        this.element = element;
        this.prev = prev;
        this.next = next;
    }

    public DoublyNode<E> linkNext(DoublyNode<E> node) {
        this.next = node;
        if (node != null) node.prev = this;
        return node;
    }

    public DoublyNode<E> linkPrev(DoublyNode<E> node) {
        this.prev = node;
        if (node != null) node.next = this;
        return node;
    }

    public Iterator<E> iterator() {
        return new Iterator<E>() {
            private DoublyNode<E> curr = DoublyNode.this;
            @Override
            public boolean hasNext() { return curr != null; }
            @Override
            public E next() {
                if (curr == null) throw new NoSuchElementException();
                E element = curr.element;
                curr = curr.next;
                return element;
            }
        };
    }

    public Iterator<E> reverseIterator() {
        return new Iterator<E>() {
            private DoublyNode<E> curr = DoublyNode.this;
            @Override
            public boolean hasNext() { return curr != null; }
            @Override
            public E next() {
                if (curr == null) throw new NoSuchElementException();
                E element = curr.element;
                curr = curr.prev;
                return element;
            }
        };
    }
}
